from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from fastapi import Depends
from typing_extensions import Annotated
from fastapi_async_sqlalchemy import db
from conf.config import mysql_config

engine = create_async_engine(
    mysql_config.ASYNC_DATABASE_URI,
    echo=mysql_config.DB_ECHO,
    future=True,
    pool_pre_ping=True,
    pool_size=mysql_config.POOL_SIZE,
    pool_recycle=mysql_config.POOL_RECYCLE,
    max_overflow=mysql_config.MAX_OVERFLOW,
    pool_timeout=mysql_config.POOL_TIMEOUT
)


async def get_db() -> AsyncSession:
    """session 生成器"""
    session = db.session
    try:
        yield session
        await session.commit()  # 在 yield 后自动提交事务
    except Exception as se:
        await session.rollback()
        raise se
    finally:
        await session.close()


# Session Annotated
DBSession = Annotated[AsyncSession, Depends(get_db)]
